package com.rhf.core.commons.properties;

import java.io.File;
import java.io.FileReader;
import java.io.Reader;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.EnvironmentConfiguration;
import org.apache.commons.configuration.PropertiesConfiguration;

/**
 * 
 * @author fabiensaulnier
 * 
 */
public class Properties extends PropertiesConfiguration {
	/**
	 * the serial version UID
	 */
	private static final long serialVersionUID = 200803080152001L;

	/**
	 * Chargement du fichier de propri�t�s
	 * 
	 * @param fileName
	 */
	protected Properties() {
		this.loadConfDirectory();
	}

	/**
	 * Initialisation du r�pertoire de l'application
	 * 
	 * @return R�pertoire de l'application
	 */
	private String getDirectory() {

		String homeDirectory = "";

		if (this.getProperty(Define.USER_HOME) == null) {
			// R�cup�ration de la configuration de l'environnement
			Configuration envConfig = new EnvironmentConfiguration();

			// R�cup�ratation du USER HOME
			homeDirectory = envConfig.getString(Define.USER_HOME);

			if ((homeDirectory != null) && (homeDirectory.length() > 0)) {
				File dir = new File(homeDirectory);

				if (dir.exists() && dir.isDirectory() && dir.canRead()) {
					this.setProperty(Define.USER_HOME, homeDirectory);
				}
			}
		}

		return homeDirectory;
	}

	/**
	 * Chargement du fichier de configuration depuis le r�pertoire de
	 * configuration (CONF DIR)
	 */
	private void loadConfDirectory() {
		// R�cup�ration du chemin du r�pertoire de l'application
		String homeDirectory = this.getDirectory();

		if (homeDirectory != null) {
			// R�cup�ration du chemin du r�pertpoire des fichiers 'properties'
			String confDirectory = homeDirectory + File.separator
					+ Define.CONF_DIR;

			File dir = new File(confDirectory);

			if (dir.exists() && dir.isDirectory() && dir.canRead()) {
				File[] listFile = dir.listFiles();

				// Chargement des fichiers
				for (int i = 0; i < listFile.length; i++) {
					File file = listFile[i];

					if (file.isFile()) {
						this.loadConfFile(file);
					}
				}
			}
		}
	}

	/**
	 * Chargement des fichiers properties
	 * 
	 * @param file
	 */
	private void loadConfFile(File file) {
		Reader io = null;

		try {
			if (file.exists() && file.canRead()) {
				// Lecture du fichier
				io = new FileReader(file);

				// Chargement du fichier comme propri�t�s
				this.load(io);
			}
		} catch (ConfigurationException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// Fermeture du flux
			if (io != null) {
				try {
					io.close();
					io = null;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}
